import 'package:flutter/material.dart';
import 'package:ribo_base_core/base_models/base_chart_axis.dart';
import 'package:ribo_base_core/base_models/base_chart_bars_lines_model.dart';
import 'package:ribo_base_core/base_models/base_chart_formatter.dart';
import 'package:ribo_base_core/base_models/base_chart_model.dart';
import 'package:ribo_base_core/base_styles/base_chart_style.dart';
import 'base_chart.dart';

class BaseChartBarsLines extends StatefulWidget {
  BaseChartBarsLines({Key key, @required this.model, this.itemPress, this.extraScript}) : super(key: key);
  final BaseChartBarsLinesModel model;
  final Function(String) itemPress;
  final String extraScript;

  @override
  _BaseChartBarsLinesState createState() => _BaseChartBarsLinesState();
}

class _BaseChartBarsLinesState extends State<BaseChartBarsLines> {
  Map<String, dynamic> _option;

  @override
  Widget build(BuildContext context) {
    _handleModel();

    return BaseChart(
      model: BaseChartModel(style: widget.model?.style, itemPress: (str) {widget.itemPress(str);}, extraScript: widget.extraScript, option: this._option),
    );
  }

  void _handleModel() {
    List<BaseChartBarsLinesSeries> series = widget.model?.series;
    BaseChartAxis baseChartAxis = BaseChartAxis();
    List<String> legends = series.map((item) => item.name).toList();
    List<String> xAxisData = [];
    series.forEach((element) {
      List list = element.data;
      list.forEach((data) {
        xAxisData.add(data.name);
      });
    });

    // xAxisData去重
    var set = new Set<String>();
    set.addAll(xAxisData);
    xAxisData = set.toList();

    List<String> xAxisDataFormat = [];
    xAxisData.forEach((element) {
      if (widget.model.isDate) {
        xAxisDataFormat.add(element.substring(element.lastIndexOf('-') + 1));
      } else {
        xAxisDataFormat.add(element);
      }
    });

    BaseChartFormatter baseChartFormatter = BaseChartFormatter.fromString('');

    this._option = {
      'legend': {
        ...BaseChartLegendStyle().toJson(),
        ...widget.model?.style?.legend?.toJson() ?? {},
        'data': legends,
      },
      'tooltip': {
        "show": widget.model?.axisTooltipFormatter != null,
        "confine": true,
        'trigger': 'axis',
        "position": "['50%', '50%']",
        "formatter": widget.model?.axisTooltipFormatter,
      },
      "xAxis": [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'category',
        }
      ],
      "yAxis": [
        {
          "type": 'value',
          "position": "left",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        },
        {
          "type": 'value',
          "position": "right",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        }
      ],
      "dataZoom": widget.model.dataZoom,
      "series": series
          .map((s) => {
                "name": s.name,
                "barGap": s.isLine == true ? null : widget.model.barGap,
                "type": s.isLine ? 'line' : 'bar',
                if (s.isLine) "smooth": true,
                "data": s.data.map((data) => data.toJson()).toList(),
                "xAxisIndex": widget.model.isHorizontal == true
                    ? (s.isLine == true
                        ? widget.model.lineAxisIndex
                        : widget.model.barAxisIndex)
                    : 0,
                "yAxisIndex": widget.model.isHorizontal != true
                    ? (s.isLine == true
                        ? widget.model.lineAxisIndex
                        : widget.model.barAxisIndex)
                    : 0,
                'itemStyle': {'color': s.isGradient ? s.gradientColor : s.color},
                if (s.markLine != null) 'markLine': s.markLine,
                "label": {
                  "show": true,
                  "position":
                      widget.model.isHorizontal == true ? 'right' : 'top',
                  "fontSize": 10,
                  "color": widget.model.barLabelColor,
                  'formatter': ((s.isLine
                              ? widget.model?.lineLabelFormatter
                              : widget.model?.labelFormatter) ??
                          baseChartFormatter)
                      .toJson()
                },
                "tooltip": widget.model.axisTooltipFormatter == null
                    ? {
                        'position': 'inside',
                        "show": true,
                        'trigger': 'item',
                        "triggerOn": "click",
                        'formatter': ((s.isLine
                                    ? widget.model?.lineTooltipFormatter
                                    : widget.model?.tooltipFormatter) ??
                                baseChartFormatter)
                            .toJson()
                      }
                    : null,
              })
          .toList()
    };

    if (widget.model?.isHorizontal == true) {
      this._option['yAxis'] = [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
          "type": 'category',
          "data": xAxisDataFormat
        }
      ];
      this._option["xAxis"] = [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'value',
          "position": "top",
        },
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'value',
          "position": "bottom",
        }
      ];

      if (widget.model?.barAxisMin != null)
        this._option['xAxis'][widget.model.barAxisIndex]['min'] =
            widget.model?.barAxisMin;
      if (widget.model?.barAxisMax != null)
        this._option['xAxis'][widget.model.barAxisIndex]['max'] =
            widget.model?.barAxisMax;
      if (widget.model?.lineAxisMin != null)
        this._option['xAxis'][widget.model.lineAxisIndex]['min'] =
            widget.model?.lineAxisMin;
      if (widget.model?.lineAxisMax != null)
        this._option['xAxis'][widget.model.lineAxisIndex]['max'] =
            widget.model?.lineAxisMax;
    } else {
      this._option['xAxis'] = [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'category',
          "data": xAxisDataFormat
        }
      ];
      this._option["yAxis"] = [
        {
          "type": 'value',
          "position": "left",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        },
        {
          "type": 'value',
          "position": "right",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        }
      ];

      if (widget.model?.barAxisMin != null)
        this._option['yAxis'][widget.model.barAxisIndex]['min'] =
            widget.model?.barAxisMin;
      if (widget.model?.barAxisMax != null)
        this._option['yAxis'][widget.model.barAxisIndex]['max'] =
            widget.model?.barAxisMax;
      if (widget.model?.lineAxisMin != null)
        this._option['yAxis'][widget.model.lineAxisIndex]['min'] =
            widget.model?.lineAxisMin;
      if (widget.model?.lineAxisMax != null)
        this._option['yAxis'][widget.model.lineAxisIndex]['max'] =
            widget.model?.lineAxisMax;

      if (widget.model?.lineAxisInterval != null)
        this._option['yAxis'][widget.model.lineAxisIndex]['interval'] =
            widget.model?.lineAxisInterval;
      if (widget.model?.barAxisInterval != null)
        this._option['yAxis'][widget.model.barAxisIndex]['interval'] =
            widget.model?.barAxisInterval;
    }
    if (widget.model.xAxisLabelFormatter != null)
      this._option['xAxis'][widget.model.barAxisIndex]['axisLabel']
          ['formatter'] = widget.model.xAxisLabelFormatter;
    if (widget.model.yAxisLabelFormatter != null)
      this._option['yAxis'][widget.model.barAxisIndex]['axisLabel']
          ['formatter'] = widget.model.yAxisLabelFormatter;
    if (widget.model.lineXAxisLabelFormatter != null)
      this._option['xAxis'][widget.model.lineAxisIndex]['axisLabel']
          ['formatter'] = widget.model.xAxisLabelFormatter;
    if (widget.model.lineYAxisLabelFormatter != null)
      this._option['yAxis'][widget.model.lineAxisIndex]['axisLabel']
          ['formatter'] = widget.model.lineYAxisLabelFormatter;
    if (widget.model.xAxisLabelRich != null)
      this._option['xAxis'][widget.model.barAxisIndex]['axisLabel']['rich'] =
          widget.model.xAxisLabelRich;
    if (widget.model.yAxisLabelRich != null)
      this._option['yAxis'][widget.model.barAxisIndex]['axisLabel']['rich'] =
          widget.model.yAxisLabelRich;
    if (widget.model.lineXAxisLabelRich != null)
      this._option['xAxis'][widget.model.lineAxisIndex]['axisLabel']['rich'] =
          widget.model.lineXAxisLabelRich;
    if (widget.model.lineYAxisLabelRich != null)
      this._option['yAxis'][widget.model.lineAxisIndex]['axisLabel']['rich'] =
          widget.model.lineYAxisLabelRich;
  }
}
